package com.example.yrdev.ordering_system.Activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.example.yrdev.ordering_system.Adapter.GoodPaymentAdapter;
import com.example.yrdev.ordering_system.Common.CommonActivity;
import com.example.yrdev.ordering_system.Common.Setting;
import com.example.yrdev.ordering_system.Dialog.GetCashDialog;
import com.example.yrdev.ordering_system.Model.Good;
import com.example.yrdev.ordering_system.Model.Operator;
import com.example.yrdev.ordering_system.Model.PurchaseReport;
import com.example.yrdev.ordering_system.R;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;
import com.example.yrdev.ordering_system.Utils.MIScanner;
import com.example.yrdev.ordering_system.Utils.MIReaderUtils;
import com.example.yrdev.ordering_system.homeOptions.PaymentDialog;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by luke on 17/11/2016.
 */

public class PaymentActivity extends CommonActivity {
    PaymentDialog paymentDialog;
    @InjectView(R.id.item_List)ListView itemList;
@InjectView(R.id.total_price)TextView total_price;

    GoodPaymentAdapter paymentAdapter;
    private GetCashDialog getCashDialog;

    private ArrayList<Good> shoppingList;
    private  String vipCardId="";

    Double totalPrice=0.;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.payment_activity_layout);
        ButterKnife.inject(this);
        setBarTitle("结算");
        showBackButton();
            initView();
        initNFCParam();

    }
    String returnMoney;


    @Override
    public void initView() {
        super.initView();
        shoppingList=(ArrayList<Good>)getIntent().getSerializableExtra("shopbag");

        checkCurrentPrice();
       Double temp=Double.valueOf( total_price.getText().toString().replace("元",""));

        getCashDialog=new GetCashDialog(this,temp);

        getCashDialog.setGetCashListener(new GetCashDialog.GetCashListener() {
            @Override
            public void payMoney(String money) {



            }

            @Override
            public void finishPayment() {
                initTicketID();

                savePurchaseRecord();
                endPayment();

            }
        });





        paymentAdapter =new GoodPaymentAdapter(this,shoppingList);
        itemList.setAdapter(paymentAdapter);



    }
    public  void  initTicketID(){
        String ticketID="1";


        int permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE);

        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {

            ticketID=GlobalFunction.getOnlyID(this);
        }
        correspondTicketId=ticketID;

    }
    public  void  endPayment(){

        if (paymentDialog!=null){
            if (paymentDialog.isShowing())
                paymentDialog.dismiss();
        }



        updateStoredNumber();
        reader.stopPrinter();

        setResult(RESULT_OK);
        finish();


    }

    private void updateStoredNumber(){

        for (Good good:shoppingList){
          good.setStoredNumber(String.valueOf(Integer.valueOf(good.getStoredNumber())-good.getPurchaseCount()));
          Good.updateGoodStoreNumber(this,good);
        }
    }
   private String correspondTicketId;

    private void savePurchaseRecord(){



        String dateTime=GlobalFunction.getCurrentDateTime();
        String httpDateTime=purchaseTime();

        ArrayList<PurchaseReport>purchaseReports=new ArrayList<>();
        String currentDate=GlobalFunction.getCurrentDate();

        for (Good good:shoppingList){

            PurchaseReport report=new PurchaseReport();
            report.setTicketID(correspondTicketId);
            report.setCommodityID(good.getId());
            report.setCommodityName(good.getName());
            report.setVolume(good.getPurchaseCount());
            report.setPrimeCost(good.getPriceIn());

            report.setSaleCost(good.getPriceOut());
            report.setCost(good.getTotalPrice());
            report.setRestoredNum(Integer.valueOf(good.getStoredNumber()));
            report.setDisCount(good.getDisoountable());
            report.setDateTime(dateTime);
            report.setDate(currentDate);
            report.setDateTimeCopy(httpDateTime);
            report.setEmployeeID(Operator.getIntance().getEmployeeID());
            report.setPayMode(payMode);
            report.setVipCardID(vipCardId);

            PurchaseReport.insertReport(this,report);

            purchaseReports.add(report);

        }


        if (Setting.getInstance().getPrintMode()){

            String receipt=  MIReaderUtils.convertToPurchaseReceipt(currentDate,correspondTicketId,vipCardId,String.valueOf(totalPrice),purchaseReports);
            reader.startPrintText(receipt);
        }



       // GlobalFunction.printTextByTag(PurchaseReport.getPurchaseReport(this).size()+"");

    }

    private String purchaseTime(){

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }






    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode==0){

    }

    }

    private void saveReport(Good good){
        String tickedID=GlobalFunction.getOnlyID(this);

    }

    private   void checkCurrentPrice(){

    try {

    for (int i=0;i<shoppingList.size();i++){
        Good goods=shoppingList.get(i);
        totalPrice=totalPrice+ Double.valueOf(goods.getTotalPrice());


    }


    total_price.setText( String.format(Locale.getDefault(),"%.2f",totalPrice)+"元");

    }catch (Exception e){


        GlobalFunction.printTextByTag("error");

    }


    }
    int payMode;

    public void cashPayment(View view){//现金消费

        getCashDialog.show();
        getCashDialog.reset();
        payMode=0;


    }

    public void cardPayment(View view){//会员卡消费
        initSwipeCardPayment();
        payMode=3;

    }
//    public void getMoney(View view){//收钱
//
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//
//        builder.setTitle("选择支付方式")
//                .setItems(R.array.paymentMethod, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                switch (which)
//                {
//                    case 0:
//                    {
//                        getCashDialog.show();
//                        getCashDialog.reset();
//                        payMode=0;
//
//                    }
//                        break;
//                    case 1:
//                    {
//                        initSwipeCardPayment();
//                        payMode=3;
//
//                    }
//                        break;
//
//                }
//                    dialog.dismiss();
//
//                    }
//
//                });
//
//
//        builder.show();
//
//
//    }



    public void initSwipeCardPayment(){

        paymentDialog  =new PaymentDialog(PaymentActivity.this,2,PaymentActivity.this);
        paymentDialog.show();
        paymentDialog.changeTitle("请刷卡");

         paymentDialog.setPaymentValue(totalPrice);

        reader.setReduceAmount(GlobalFunction.convertToInt(totalPrice*100));
        reader.setOperate(1);//允许写卡
        reader.setAction(1);
        reader.setPurchaseMode(6);//商品消费
        paymentDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                reader.reset();
            }
        });
        paymentDialog.setCallBack(new PaymentDialog.callBack() {
            @Override
            public void getCurAmount(Integer amount) {
            processCardState=true;

                reader.setReduceAmount(amount);
            }

            @Override
            public void done() {


                new java.util.Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {


                        endPayment();

                    }

                },1500);




            }

            @Override
            public void standbyMode() {

            }
        });
        reader.setCallback(new MIScanner.Callback() {
            @Override
            public void showFixPurchaseCost(Double cost) {

            }

            @Override
            public void getCardInfo(Double reduceAmount,Double remain,Double currentBalance) {

                paymentDialog.showOtherNominal(reduceAmount,remain,currentBalance);

            }

            @Override
            public void getMICardNo(String cardNo,String ticketID) {
                GlobalFunction.printTextByTag("cardNo:"+cardNo);
                vipCardId=cardNo;
                correspondTicketId=ticketID;

                savePurchaseRecord();

            }
        });
    }


    //for reading MI CARD
    @Override
    protected void onResume() {
        super.onResume();

        try {
            reader.processIntent(mNfcAdapter,getIntent());
        }catch (Exception e){

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {

            reader.processIntent(mNfcAdapter, intent);
        } catch (Exception e) {

        }
    }

}
